package com.springboot.frame.enums;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liheng
 * @ClassName PersonType
 * @Description
 * @date 2020-12-28 11:30
 * @JsonFormat(shape = JsonFormat.Shape.STRING)  ---> "STUDENT"
 * @JsonFormat(shape = JsonFormat.Shape.OBJECT)  ---> "{
 * "code": "a",
 * "text": "学生"
 * }"
 */
@JsonFormat
public enum SexType implements BaseEnum<SexType, String> {
    STUDENT("1", "男"),
    TEACHER("0", "女");

    private String code;
    @JsonValue
    private String text;

    SexType(String code, String text) {
        this.code = code;
        this.text = text;
    }

    @Override
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public static Map<String, SexType> enumMap = new HashMap<String, SexType>();

    static {
        for (SexType type : SexType.values()) {
            enumMap.put(type.getCode(), type);
        }
    }

    public static SexType getEnum(String code) {
        return enumMap.get(code);
    }

    /**
     * 用于兼容 @RequestBody 传参
     * 使用@RequestBody会不走EnumConvertFactory的方法,@RequestBody默认通过下标查找
     * @param code
     * @return
     *
     * https://zhuanlan.zhihu.com/p/101610039
     */
    @JsonCreator
    public static SexType findLevelEmum(String code) {
        for (SexType item : SexType.values()) {
            if (item.getCode().equals(code)) {
                return item;
            }
        }
        return null;
    }
}
